<template>
  <div class="app-container">

    <el-button type="primary" @click="handleAddRole">新增</el-button>
    <div style="height:650px">
      <el-table :data="rolesList" v-loading='loading' style="width: 100%;margin-top:30px;" border>
        <el-table-column label="bannerID">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="banner图片地址">
          <template slot-scope="scope">
            <img :src="scope.row.resources" :alt="scope.row.resources" style="width: 100px; height: 50px;" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="banner上传时间">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)">修改</el-button>
            <el-popconfirm title="是否删除" @confirm='handleDelete(scope.row)'>
              <el-button slot="reference" type="danger">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>

      </el-table>
    </div>

    <!-- 添加对话框 -->
    <el-dialog :visible.sync="createDialogVisible" @close="handleCancel" :close-on-click-modal="false" :title="isAddOrUpdata?'新增banner':'修改banner'">
      <el-form :rules="rules" ref="ruleForm" :model="ruleForm" label-width="150px" v-loading='loading'>
        <el-form-item label="上传图片" prop="resources">
          <el-upload :data='{dirName:""}' :headers="headers" :limit="1" list-type="picture-card" ref="uploadIMG" :file-list="fileList" :on-error="fileError" :on-remove="handleRemove" :action="uploadPath" :auto-upload="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload1" :on-change="beforeAvatarUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="图片排序：" prop="sortNum">
                        <el-input v-model="ruleForm.sortNum" />
                      </el-form-item>
                       <el-form-item label="图片链接：" prop="link">
                        <el-input v-model="ruleForm.link" />
                      </el-form-item> -->

        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button :loading='loading' type="primary" @click="handlePublish">保存</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    <el-pagination background layout="prev, pager, next,sizes,total" :total='total' @current-change='current_change' @size-change='size_change' style="text-align: center; margin-top: 60px;" :page-sizes="[10, 50, 100, 1000]">
    </el-pagination>

  </div>
</template>

<script>
import api from '@/api/gameBox/banner'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
export default {
  name: 'banner',
  data() {
    return {
      isImgCheak: false,
      isAddOrUpdata: true, // true新增false修改
      createDialogVisible: false,
      uploadPath: uploadPath,
      rolesList: [],
      fileList: [],
      total: 0,
      limit: '',
      page: '',
      pages: '',
      loading: false,
      ruleForm: {
        resources: '',
        gameId: ''
        // link:'',
        // sortNum:1
      },
      rules: {
        // link: [{ required: true, message: '请输入版本名称', trigger: 'blur' }],
        // sortNum: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        // resources:[{ required: true, message: '请填上传正确格式的图片', trigger: 'change' }],
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Hyxxkj-Admin-Token': getToken()
      }
    }
  },
  created() {},
  mounted() {
    if (this.$route.query.id == null) {
      return
    }
    this.ruleForm.gameId = this.$route.query.id
    this.getList()
  },
  methods: {
    handleRemove() {
      // 移除图片
      this.ruleForm.resources = ''
    },
    beforeAvatarUpload1(file) {
      // 图片改变
      console.log(file)
      this.isImgCheak = true
      var isJPG = false
      if (
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'video/mp4'
      ) {
        isJPG = true
      }
      const isLt2M = file.size / 1024 / 1024 < 100

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF/mp4 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return
      }
      this.ruleForm.resources = URL.createObjectURL(file)

      return isJPG && isLt2M
    },
    beforeAvatarUpload(file) {
      // 图片改变
      this.isImgCheak = true
      var isJPG = false
      if (
        file.raw.type === 'image/jpeg' ||
        file.raw.type === 'image/png' ||
        file.raw.type === 'image/gif' ||
        file.raw.type === 'video/mp4'
      ) {
        isJPG = true
      }
      const isLt2M = file.size / 1024 / 1024 < 100

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF/mp4 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return
      }
      this.ruleForm.resources = URL.createObjectURL(file.raw)

      return isJPG && isLt2M
    },

    handleAvatarSuccess(res, file) {
      // 上传成功
      if (res.errno == 0) {
        this.ruleForm.resources = res.data.url
        if (this.isAddOrUpdata) {
          this.Create(this.ruleForm)
        } else {
          this.update(this.ruleForm)
        }
      }
    },
    fileError(err, file, fileList) {
      // 上传出错
      this.ruleForm.resources = ''
      this.$message({
        message: '上传出错',
        type: 'warning'
      })
    },

    handleAddRole() {
      // 新增对话框
      this.isAddOrUpdata = true
      this.createDialogVisible = true
    },
    handlePublish() {
      // 新增图片
      if (this.ruleForm.resources == '') {
        this.$message({
          message: '请选择文件',
          type: 'warning'
        })
        return
      }
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (!this.isAddOrUpdata && !this.isImgCheak) {
            this.update(this.ruleForm)
          } else {
            this.$refs.uploadIMG.submit()
          }
        } else {
          this.$message({
            message: '请检查数据必填项',
            type: 'warning'
          })
          return false
        }
      })
    },
    handleCancel() {
      this.createDialogVisible = false
      this.ruleForm.resources = ''
      this.ruleForm.link = ''
      this.ruleForm.sortNum = 1
      this.fileList = []
    },
    handleEdit(e) {
      this.isAddOrUpdata = false
      ;(this.ruleForm.resources = e.resources),
      (this.ruleForm.link = e.link),
      (this.ruleForm.sortNum = e.sortNum),
      (this.ruleForm.id = e.id)
      this.fileList.push({
        url: e.resources
      })
      this.createDialogVisible = true
    },
    handleDelete(e) {
      api.Delete(e).then((res) => {
        if (res.data.errno == 0) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getList()
        }
      })
    },
    current_change(e) {
      this.page = e
      this.getList()
    },
    size_change(e) {
      this.limit = e
      this.getList()
    },
    Create(e) {
      this.loading = true
      api
        .create(e)
        .then((res) => {
          if (res.data.errno == 0) {
            this.loading = false
            this.$message({
              message: '新增成功',
              type: 'success'
            })
            this.getList()
            this.createDialogVisible = false
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message({
            message: e.data,
            type: 'warning'
          })
        })
    },
    update(e) {
      this.loading = true
      api
        .update(e)
        .then((res) => {
          if (res.data.errno == 0) {
            this.loading = false
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.getList()
            this.createDialogVisible = false
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message({
            message: e.data,
            type: 'warning'
          })
        })
    },
    getList() {
      this.loading = true
      const id = this.$route.query.id
      api
        .list({ gameId: id })
        .then((res) => {
          if (res.data.errno == 0) {
            this.rolesList = res.data.data.list
            this.total = res.data.data.list.length
            this.page = res.data.data.page
            this.pages = res.data.data.pages
            this.total = res.data.data.total
            this.limit = res.data.data.limit
            this.loading = false
          }
        })
        .catch(() => {
          this.Loading = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
</style>